import asyncio
from tkinter import messagebox, simpledialog, Tk
from googletrans import Translator

async def translate_text(input_text):
    translator = Translator()
    # 异步调用翻译方法
    translation = await translator.translate(input_text, dest='zh-CN')
    return translation.text

async def main():
    root = Tk()
    root.withdraw()
    try:
        input_text = simpledialog.askstring("输入英文", "请输入要翻译的英文:")
        if input_text:
            if input_text == "exit":
                root.destroy()
                messagebox.showinfo("安全退出", "已安全退出程序！\nMade by Tianlang\nVersion 1.0")
                exit()
            result = await translate_text(input_text)
            messagebox.showinfo("翻译结果", f"翻译结果: {result}")
            #存储翻译结果到文件
            #utf-8格式
            with open("Translator\\translation_result.txt", "a", encoding="utf-8") as file:
                file.write(f"{input_text} -> {result}\n")
    except Exception as e:
        messagebox.showerror("错误", f"发生错误: {str(e)}")

if __name__ == "__main__":
    while True:
        asyncio.run(main())